<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn-debounce">防抖</button>
  <button id="btn-throttle">节流</button>
  <script>
  /**
   * 防抖：debounce
   *  触发高频事件后n秒内函数只会执行一次，如果n秒内高频事件再次被触发，则重新计算时间
   * 节流：throttle 
   *  高频事件触发，但在n秒内只会执行一次，所以节流会稀释函数的执行频率
   */
    function click() {
      console.log('click');
    }
    let btnDebounce = document.getElementById('btn-debounce');
    let btnThrottle = document.getElementById('btn-throttle');

    function debounce(call) {
      let timer = null
      return function () {
        clearTimeout(timer) 
        timer = setTimeout(() => {
          call()
        }, 1000);
      }
    }

    function throttle(call) {
      let canRun = true
      return function () {
        if (!canRun) return
        canRun = false
        setTimeout(() => {
          call()
          canRun = true
        }, 1000);
      }
    }
    btnDebounce.onclick = debounce(click); 
    btnThrottle.onclick = throttle(click);
  </script>
</body>
</html>

